package com.langxin.erp.util.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.langxin.erp.model.UserInfo;
import com.langxin.erp.util.constant.SiteConstant;
import com.langxin.erp.util.security.Base64Code;

/**
 * 请求相关的工具类
 * 
 */
public class ActionUtils {
	
    /**
     * Spring MVC获取request的三种方法：
     * <a href="http://yeelor.iteye.com/blog/1554795">http://yeelor.iteye.com/blog/1554795</a> 
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
    }
    
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getResponse();
    }
    
    /**获取请求IP*/
    public static String getIP() {
        HttpServletRequest request = ActionUtils.getRequest();
        String addr = request.getRemoteAddr();
        //haproxy代理后把真实访问ip放在http header的 “X-Forwarded-For”中
        String headerXForwardedFor = request.getHeader("X-Forwarded-For");
        return headerXForwardedFor == null ? addr : headerXForwardedFor;
    }

    /**获取服务器真实路径*/
    public static String getRealPath(String path) {
        HttpServletRequest request = ActionUtils.getRequest();
        return request.getSession().getServletContext().getRealPath(path);
    }
    
    /**
     * 获取当前登录的用户
     * @return
     */
    public static UserInfo getCurrentUser(){
    	// 从session中获取
    	Object user =  getRequest().getSession().getAttribute(SiteConstant.SESSION_USER_KEY);
    	if(user != null){
    		return (UserInfo)user;
    	}else{
    		// 从cookie中获取
        	String value = CookieUtil.getCookieValue(ActionUtils.getRequest(), SiteConstant.CookieKey.USER_COOKIE.getValue());
        	if(StringUtils.isNotBlank(value)){
        		value = Base64Code.decode(value);
        		 UserInfo userInfo = JsonUtils.fromJson(value, UserInfo.class);
        		 getRequest().getSession().setAttribute(SiteConstant.SESSION_USER_KEY, userInfo);
        		 return userInfo;
        	}else{
        		return null;
        	}
    	}
    }
}
